<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>博客编辑页</title>
    <link rel="stylesheet" href="css/common.css">
    <link rel="stylesheet" href="css/edit.css">
    <link rel="stylesheet" href="blog-editormd/css/editormd.css" />
</head>
<body>
    <div class="nav">
        <img src="pic/pig.jpg" alt="">
        <span class="blog-title">01Blog</span>
        <a class="nav-span" href="blog_list.html">首页</a>
        <a class="nav-span" href="category.html">文章分类</a>
        <a class="nav-span" href="tag.html">文章标签</a>
        <a class="nav-span" href="blog_edit.html">写博客</a>
        <div id="user-info" class="nav-span"></div> <!-- 用户信息显示位置 -->
    </div>
    
    <div class="content-edit">
        <div class="push">
            <input type="hidden" id="blogId">
            <input type="text" name="" id="title">
            <input type="button" value="更新文章" id="submit" onclick="submit()">
        </div>
        
        <div class="push">
            <input type="text" name="" id="tag" value="">
            <input type="text" name="" id="cage" value="">
        </div>

        <div id="editor">
            <textarea style="display:none;" id="content"></textarea>    
        </div>
    </div>

    <script src="js/jquery.min.js"></script>
    <script src="blog-editormd/editormd.min.js"></script>
    <script src="js/main.js"></script>
    <script type="text/javascript">
        document.addEventListener('DOMContentLoaded', () => {
            // 动态显示用户信息
            const userDiv = document.getElementById('user-info');
            const userInfo = localStorage.getItem('userInfo');
            if (userInfo) {
                const user = JSON.parse(userInfo);
                userDiv.innerHTML = `
                    <span>用户名: ${user.account}</span>
                    <button onclick="logout()">登出</button>
                `;
            } else {
                userDiv.innerHTML = `
                    <button onclick="redirectTo('login.html')">登录</button>
                    <button onclick="redirectTo('register.html')">注册</button>
                `;
            }

            // 加载文章详情
            let aid = window.location.search.slice(1).split('=')[1];
            fetch(`http://localhost:8888/articles/updateGetDetail/${aid}`)
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        const article = data.data;
                        $("#blogId").val(article.id);
                        $("#title").val(article.title);
                        $("#tag").val(article.tag);
                        $("#cage").val(article.category);
                        editormd("editor", {
                            width  : "100%",
                            height : "100%",
                            path   : "blog-editormd/lib/",
                            onload : function() {
                                this.watch();
                                this.setMarkdown(article.content);
                            }
                        });
                    } else {
                        document.querySelector('.content-edit').innerHTML = '<p>无法获取文章详情</p>';
                    }
                })
                .catch(error => {
                    console.error('Error fetching article details:', error);
                    document.querySelector('.content-edit').innerHTML = '<p>无法获取文章详情</p>';
                });

            // 更新文章的提交函数
            window.submit = async function() {
    const userInfo = localStorage.getItem('userInfo');
    let account = '';

    if (userInfo) {
        const user = JSON.parse(userInfo);
        account = user.account;
    }

    const blogId = $("#blogId").val(); // 获取文章ID

    try {
        // 首先删除文章
        const deleteResponse = await fetch(`http://localhost:8888/articles/delete/${blogId}`, {
            method: 'DELETE',
        });
        const deleteResult = await deleteResponse.json();
        if (deleteResult.code !== 200) {
            throw new Error('删除文章失败');
        }

        // 删除成功后发布文章
        const publishResponse = await fetch("http://localhost:8888/articles/publish", {
            method: "POST",
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `title=${encodeURIComponent($("#title").val())}&content=${encodeURIComponent($("#content").val())}&tag=${encodeURIComponent($("#tag").val())}&category=${encodeURIComponent($("#cage").val())}&account=${encodeURIComponent(account)}`
        });
        const publishResult = await publishResponse.json();
        if (publishResult.code === 200) {
            location.href = "blog_list.html"; // 成功后跳转
        } else {
            alert("博客发布失败!");
        }
    } catch (error) {
        alert(error.message);
    }
};

        });
    </script>
</body>
</html>
